package org.example.ideavr.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.example.ideavr.common.properties.JwtProperties;
import org.example.ideavr.common.result.Result;
import org.example.ideavr.common.utils.JwtUtils;
import org.example.ideavr.pojo.dto.UserDTO;
import org.example.ideavr.pojo.dto.UserLoginDTO;
import org.example.ideavr.pojo.dto.UserRegisterDTO;
import org.example.ideavr.pojo.entity.User;
import org.example.ideavr.pojo.vo.UserVO;
import org.example.ideavr.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Tag(name = "User模块")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    JwtProperties jwtProperties;
    @Autowired
    UserService userService;

    /**
     * 用户登录接口
     */
    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result<UserVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录:{}",userLoginDTO);

        //登录service检验返回用户数据
        User user = userService.login(userLoginDTO);

        //创建jwt
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        String token = JwtUtils.generateJwt(jwtProperties.getTtl(), jwtProperties.getSecretKey(),claims);
        log.info("生成的token:{}",token);

        //封装vo返回
        UserVO userVO = UserVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .email(user.getEmail())
                .imgUrl(user.getImgUrl())
                .token(token)
                .status(user.getStatus())
                .build();
        return Result.success(userVO);
    }

    /**
     * 用户注册
     */
    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public Result<String> register(@RequestBody UserRegisterDTO userRegisterDTO) {
        log.info("用户注册:{}",userRegisterDTO);
        userService.register(userRegisterDTO);
        return Result.success();
    }

    /**
     * 根据id查询用户
     */
    @Operation(summary = "根据id查询用户")
    @GetMapping("/{id}")
    public Result<UserVO> getUserById(@PathVariable("id") Long id) {
        log.info("根据id查询用户:{}",id);
        UserVO userVO = userService.getUserById(id);
        return Result.success(userVO);
    }

    /**
     * 修改用户
     */
    @Operation(summary = "修改用户")
    @PutMapping("/update")
    public Result<String> updateUser(@RequestBody UserDTO userDTO) {
        log.info("修改用户:{}",userDTO);
        userService.updateUser(userDTO);

        return Result.success();
    }
}
